/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package at.alexanderpehm.pony.controller;

import at.alexanderpehm.pony.model.NoteInfo;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Application;
import org.jdesktop.application.ResourceMap;

/**
 * 
 * @author Alexander Pehm
 */
public class NoteBookDAO {

    private ResourceMap resourceMap = Application.getInstance(at.alexanderpehm.pony.PonyApp.class).getContext().getResourceMap(NoteBookDAO.class);
    private static String currentNotebookPath = null;

    public static String getCurrentNotebookPath() {
        if (currentNotebookPath == null) {
            return getDefaultNotebookPath();
        }
        return currentNotebookPath;
    }

    public static void setCurrentNotebookPath(String newNotebookPath) {
        currentNotebookPath = newNotebookPath;
    }

    private static String getDefaultNotebookPath() {
        //TODO This doesb't seem to work
        //return resourceMap.getString("Notebook.defaultPath");
        return "/";
    }

    /**
     * Creates a new note. By default, new notes are created in a subdirectory
     * relative to the current notebook directory.
     * @param note the note to create.
     * @return Note containing the path of the note, relative to the current notebook.
     */
    public NoteInfo createNote(NoteInfo note) {

        String relativeFilename = note.getTitle() + File.separator;
        String absolutePath = getCurrentNotebookPath();
        File file = new File(absolutePath + relativeFilename);
        int suffixCount = 0;

        if (file.exists()) {
            relativeFilename = relativeFilename.substring(0, relativeFilename.length() - 1);
            String tempFileName = null;
            while (file.exists()) {
                suffixCount++;
                tempFileName = absolutePath + relativeFilename + "_" + suffixCount + File.separator;
                file = new File(tempFileName);
            }
            relativeFilename += "_" + suffixCount + File.separator;
        }
        try {
            file.mkdir();
            File outFile = new File(absolutePath + relativeFilename + "note.html");

            InputStream in = this.getClass().getClassLoader().getResourceAsStream("at/alexanderpehm/pony/controller/note.html");

            OutputStream out = new FileOutputStream(outFile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();

            System.out.println("Template URL: " + this.getClass().getClassLoader().getResource("at/alexanderpehm/pony/controller/note.html"));


            note.setRelativePath(relativeFilename);
            note.setTitle(file.getName());
            return note;
        } catch (IOException ex) {
            Logger.getLogger(NoteBookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        //TODO throw technical Exception
        return note;
    }

    public void updateNote(NoteInfo noteInfo, String payload) {
        String notePath = NoteBookDAO.getCurrentNotebookPath() + noteInfo.getRelativePath() + File.separator + "note.html";
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(notePath));
            bw.write(payload);
            bw.close();
        } catch (IOException ex) {
            Logger.getLogger(NoteBookDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Rename a note
     * @param oldNote
     * @param newInfo
     */
    public NoteInfo renameNote(NoteInfo oldNote, String newNoteName) {
        File oldFile = new File(NoteBookDAO.getCurrentNotebookPath() + oldNote.getRelativePath());
        File newFile = new File(oldFile.getParent() + File.separator + newNoteName);
        System.out.println("New File: " + newFile.getAbsolutePath());
        String newRelativePath = oldNote.getRelativePath().replace(oldNote.getTitle(), newNoteName);
        oldNote.setRelativePath(newRelativePath);
        oldNote.setTitle(newNoteName);
        oldFile.renameTo(newFile);
        return oldNote;
    }

    public String readNote(NoteInfo noteInfo) {
        String notePath = NoteBookDAO.getCurrentNotebookPath() + noteInfo.getRelativePath() + File.separator + "note.html";
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(notePath));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(NoteBookDAO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException io) {
            Logger.getLogger(NoteBookDAO.class.getName()).log(Level.SEVERE, null, io);
        }
        return buffer.toString();
    }

    /**
     * Retrieve the list of attachments for a particular note.
     * Returns an ampty List if the note has no attachments.
     * @param note
     * @return
     */
    public String[] getAttachments(NoteInfo note) {
        File attachmentDir = new File(NoteBookDAO.getCurrentNotebookPath() + note.getRelativePath());
        String[] noteDirContent = attachmentDir.list();
        return noteDirContent;
    }
}
